import express from "express";
import bodyParser from "body-parser";
import sessions from "cookie-session";
import cookieParser from "cookie-parser";
import multer from "multer";
import morgan from "morgan";
import uuid from "uuid";

let server = express();

//静态资源服务器
server.use(express.static("./../src"));
// server.use(express.static("./public"));
//配中间件

server.use(morgan("combined"));
// server.use(morgan('combined', {stream : fs.createWriteStream("./logs/logs.log",{flags:'a'})})); // a append
server.use(bodyParser.urlencoded({
    extended: false,
}));
server.use(bodyParser.json());
server.use(cookieParser("useker.cn")); //cookie的签名
// server.use(sessions({
//     genid: function () {
//         return uuid.v4;
//     },
//     secret: "useker.cn",
//     maxAge: 20 * 60 * 1000,
//     saveUninitialized: true,
//     resave: true,
// // }));

server.use(sessions({
    name: "useker.cn",
    keys: ["aaa", "bbb", "ccc", "dddd"],
    maxAge: 1000 * 60 * 20
}))


let multerObj = multer({
    dest: "./public/upload"
})
server.use(multerObj.any());

//跨域和响应编码内容
server.all("*", (request, response, next) => {
    response.setHeader("Content-Type", "application/json;charset=utf-8");
    response.setHeader("Access-Control-Allow-Origin", "*"); //跨域
    // next();
    // response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500"); //跨域

    // response.setHeader('Access-Control-Allow-Credentials', 'true');
    // response.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Referer, User-Agent, Authorization, X-Auth-Token');
    //如果是访问了登录接口或注册接口,就可以直接访问
    if (request.originalUrl == "/api/login" || request.originalUrl == "/api/reg" || request.originalUrl.indexOf("/api/checkUname") !== -1) {
        console.log(request.query, 2)
        next();
    } else {
        //要判断有么有登录
        if (!request.query.uid) {
            if (request.body.uid) {
                next();
            } else {
                console.log(request.query, 1)
                response.json({
                    msg: "您还没登录,请先行登录",
                    status: -1
                })
            }
        } else {
            next();
        }
    }
})

//让保安大爷 正式接管 api大楼
server.use("/api", require("./routes/ApiRoute"));


server.listen(8080, () => {
    console.log("服务启动完毕");
})